package com.tzxs.pay.main.print;

import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.ViewModelProviders;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.ActivityPrintAllBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.print.utils.print.AidlUtil;
import com.tzxs.pay.main.print.viewmodel.PrintViewModel;
import com.tzxs.pay.util.StatusBarColorSetter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

//打印汇总
public class PrintAllActivity extends BaseActivity<ActivityPrintAllBinding> {
    private static final String TAG = PrintAllActivity.class.getSimpleName();
    private String startTimeStr = "";//开始时间
    private String endTimeStr = "";//结束时间
    private int timeType = 1;//时间类型
    private PrintViewModel viewModel;

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_print_all;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        AidlUtil.getInstance().initPrinter();
        viewModel = ViewModelProviders.of(this).get(PrintViewModel.class);
        dataBinding.printAllToolbar.setNavigationOnClickListener(v -> onBackPressed());
        //默认显示打印汇总
        dataBinding.printAll.setSelected(true);
        //默认选中今天
        dataBinding.today.setSelected(true);
        //汇总
        dataBinding.allLay.setOnClickListener(v -> {
            clearPrintStatus();
            dataBinding.printAll.setSelected(!dataBinding.printAll.isSelected());
        });
        //未结算汇总
        dataBinding.nsettlementLay.setOnClickListener(v -> {
            dataBinding.printAll.setSelected(false);
            dataBinding.printAllNoset.setSelected(!dataBinding.printAllNoset.isSelected());
        });
        dataBinding.nsettlementDetail.setOnClickListener(v -> {
            dataBinding.printAll.setSelected(false);
            dataBinding.printNosetDetail.setSelected(!dataBinding.printNosetDetail.isSelected());
        });
        //今天
        dataBinding.today.setOnClickListener(v -> {
            clearTimeStatus();
            dataBinding.today.setSelected(!dataBinding.today.isSelected());
            timeType = 1;
            //重制选择时间
            dataBinding.startTime.setText("");
            dataBinding.endTime.setText("");
        });
        //昨天
        dataBinding.yesterday.setOnClickListener(v -> {
            clearTimeStatus();
            dataBinding.yesterday.setSelected(!dataBinding.yesterday.isSelected());
            timeType = 2;
            //重制选择时间
            dataBinding.startTime.setText("");
            dataBinding.endTime.setText("");
        });
        //本周
        dataBinding.thisWeek.setOnClickListener(v -> {
            clearTimeStatus();
            dataBinding.thisWeek.setSelected(!dataBinding.thisWeek.isSelected());
            timeType = 3;
            //重制选择时间
            dataBinding.startTime.setText("");
            dataBinding.endTime.setText("");
        });
        //选择开始时间
        dataBinding.startTime.setOnClickListener(v -> {
            clearTimeStatus();
            chooseTime(dataBinding.startTime, 0);
            timeType = 0;
        });
        //选择结束时间
        dataBinding.endTime.setOnClickListener(v -> {
            clearTimeStatus();
            chooseTime(dataBinding.endTime, 1);
            timeType = 0;
        });
        //打印当前条件的内容
        dataBinding.print.setOnClickListener(v -> {
            if (!dataBinding.today.isSelected() && !dataBinding.yesterday.isSelected() &&
                    !dataBinding.thisWeek.isSelected()) {
                if (TextUtils.isEmpty(dataBinding.startTime.getText().toString())
                        || TextUtils.isEmpty(dataBinding.endTime.getText().toString())) {
                    Toast.makeText(this, "请选择完整时间段", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (dataBinding.printAll.isSelected()) {
                viewModel.printAll(timeType, startTimeStr, endTimeStr, () -> {
                    //获取打印内容成功
                    printContent(viewModel.printAll);
                });
            } else {
                if (dataBinding.printAllNoset.isSelected() && !dataBinding.printNosetDetail.isSelected()) {
                    //单选
                    viewModel.unsetPrint(timeType, startTimeStr, endTimeStr, "1", null, () -> {
                        printContent(viewModel.printList);
                    });
                } else if (dataBinding.printNosetDetail.isSelected() && !dataBinding.printAllNoset.isSelected()) {
                    //单选
                    viewModel.unsetPrint(timeType, startTimeStr, endTimeStr, null, "1", () -> {
                        printContent(viewModel.printList);
                    });
                } else {
                    if (timeJudge(endTimeStr) < timeJudge(endTimeStr)) {
                        Toast.makeText(this, "结束时间不能小于开始时间", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //多选
                    viewModel.unsetPrint(timeType, startTimeStr, endTimeStr, "1", "1", () -> {
                        printContent(viewModel.printList);
                    });
                }
            }
        });
    }

    //判断时间段选择
    private long timeJudge(String time) {
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        simpleDateFormat.applyPattern("yyyy-MM-dd");
        try {
            Date date = simpleDateFormat.parse(time);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    //打印内容
    private void printContent(ArrayList<String> content) {
        AidlUtil aidlUtil = AidlUtil.getInstance();
        if (Build.MODEL.contains("T2")) {
            Log.d(TAG, "content.get(0): " + content.get(0));
            aidlUtil.printText(content.get(0) + '\n', "32", "32", "1", true, false);
            Log.d(TAG, "content.get(1): " + content.get(1));
            aidlUtil.printText(content.get(1) + '\n', "24", "24", "1", false, false);
            String mainContent = content.get(2).replace("\\n", "\n");
            mainContent = mainContent.replace(" ", "");
            Log.d(TAG, "mainContent: " + mainContent);
            aidlUtil.printText(mainContent + '\n', "24", "24", "0", false, false);
            String last = content.get(3).replace("\\n", "\n");
            last = last.replace(" ", "");
            Log.d(TAG, "last: " + last);
            aidlUtil.printText(last + "\n\n", "24", "24", "1", false, false);
            aidlUtil.cutPaper(null);
        } else {
            aidlUtil.enterPrinterBuffer(true);
            aidlUtil.printText(content.get(0), "32", "32", "1", true, false);
            aidlUtil.printBlankLine("1", "10");
            aidlUtil.printText("\n" + content.get(1), "24", "24", "1", false, false);
            aidlUtil.printBlankLine("1", "10");
            String mainContent = content.get(2).replace("\\n", "\n");
            aidlUtil.printText(mainContent, "24", "24", "0", false, false);
            aidlUtil.printText(content.get(3), "24", "24", "1", false, false);
            aidlUtil.printBlankLine("5", "30");
            aidlUtil.printCommit();
        }
    }

    //清除所有的选中状态
    private void clearPrintStatus() {
        dataBinding.printAll.setSelected(false);
        dataBinding.printAllNoset.setSelected(false);
        dataBinding.printNosetDetail.setSelected(false);
    }

    //清除选中按钮
    private void clearTimeStatus() {
        dataBinding.today.setSelected(false);
        dataBinding.yesterday.setSelected(false);
        dataBinding.thisWeek.setSelected(false);
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        format.applyPattern("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * 选择时间
     *
     * @param id 控件id
     */
    private void chooseTime(TextView timeView, int id) {
        Log.d(TAG, "chooseTime: 选择时间:");
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(PrintAllActivity.this, (date, v) -> {
            timeView.setText(getTime(date));
            switch (id) {
                case 0:
                    startTimeStr = getTime(date);
                    break;
                case 1:
                    endTimeStr = getTime(date);
                    break;
            }

        })
                .setType(new boolean[]{true, true, true, true, true, true})
                .isDialog(true)
                .build();
        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
            mDialog.show();
        }
    }
}